import React, { PureComponent, Fragment } from 'react';
import {
  Card,
  Table,
  Button,
  Form,
  Alert,
  Modal,
  Icon,
  Input,
  Divider,
} from 'antd';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from "./Menu.less";

const FormItem = Form.Item;

/**
 * 新增或编辑角色组件, 根据传值与否控制
 */
@connect(({ authMenu, loading }) => ({
  authMenu,
  loading: loading.models.authMenu,
}))
@Form.create()
class AddOrUpdateForm extends PureComponent {

  okHandle = () => {
    const { form, handleAdd, handleUpdate, values } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if (values && Object.keys(values).length) {
        handleUpdate(fieldsValue)
      } else {
        handleAdd(fieldsValue);
      }
    });
  }

  render() {
    const { modalVisible, form, handleModalVisible, values } = this.props;
    return (
      <Modal
        destroyOnClose
        title={values && Object.keys(values).length ? "编辑菜单" : "新增菜单"}
        visible={modalVisible}
        onOk={this.okHandle}
        onCancel={() => handleModalVisible(false)}
      >
        <Form>
          <div>
            {form.getFieldDecorator('uid', {
              initialValue: values && Object.keys(values).length ? values.uid : null,
            })(
              <Input type="hidden" />
            )}
          </div>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="描述">
            {form.getFieldDecorator('menuDesc', {
              initialValue: values && Object.keys(values).length ? values.menuDesc : null,
              rules: [{ required: true, message: '描述必填！' }],
            })(
              <Input />
            )}
          </FormItem>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="父ID">
            {form.getFieldDecorator('parentId', {
              initialValue: values && Object.keys(values).length ? values.parentId : null,
              rules: [{ required: true, message: '父ID必填！' }],
            })(
              <Input />
            )}
          </FormItem>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="ID">
            {form.getFieldDecorator('menuId', {
              initialValue: values && Object.keys(values).length ? values.menuId : null,
              rules: [{ required: true, message: 'ID必填！' }],
            })(
              <Input />
            )}
          </FormItem>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="名称">
            {form.getFieldDecorator('menuName', {
              initialValue: values && Object.keys(values).length ? values.menuName : null,
              rules: [{ required: true, message: '名称必填！' }],
            })(
              <Input />
            )}
          </FormItem>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="路由">
            {form.getFieldDecorator('menuPath', {
              initialValue: values && Object.keys(values).length ? values.menuPath : null,
              rules: [{ required: true, message: '路由必填！' }],
            })(
              <Input />
            )}
          </FormItem>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="图标">
            {form.getFieldDecorator('icon', {
              initialValue: values && Object.keys(values).length ? values.icon : null,
            })(
              <Input />
            )}
          </FormItem>
        </Form>
      </Modal>
    );
  }
}

/* eslint react/no-multi-comp:0 */
@connect(({ authMenu, loading }) => ({
  authMenu,
  loading: loading.models.authMenu,
}))
class MenuList extends PureComponent {
  state = {
    modalVisible: false,
    selectedRowKeys: [],
    stepFormValues: {},
  };


  columns = [
    {
      title: '描述',
      dataIndex: 'menuDesc'
    },
    {
      title: '父ID',
      dataIndex: 'parentId'
    },
    {
      title: 'ID',
      dataIndex: 'menuId'
    },
    {
      title: '名称',
      dataIndex: 'menuName'
    },
    {
      title: '路由',
      dataIndex: 'menuPath'
    },
    {
      title: '图标',
      dataIndex: 'icon',
      render: val => {
        return <Icon type={val} />;
      }
    },
    {
      title: '操作',
      width: 200,
      render: (record) => (
        <Fragment>
          <a onClick={() => this.handleModalVisible(true, record)}>编辑</a>
          <Divider type="vertical" />
          <a onClick={() => this.handleDel(record)}>删除</a>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    this.listData()
  }

  /**
   * 表格多选
   */
  handleSelectRows = selectedRowKeys => {
    console.log(selectedRowKeys)
    this.setState({
      selectedRowKeys,
    });
  };

  /**
   * 控制编辑模态
   */
  handleModalVisible = (flag, record) => {
    this.setState({
      modalVisible: !!flag,
      stepFormValues: record || {},
    });
  };

  /**
   * 新增
   */
  handleAdd = fields => {
    const { dispatch } = this.props;
    console.log(fields)
    dispatch({
      type: 'authMenu/add',
      payload: {
        ...fields
      },
    })
    this.handleModalVisible();
  };

  /**
   * 更新
   */
  handleUpdate = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'authMenu/update',
      payload: {
        ...fields
      },
    })
    this.handleModalVisible();
  };


  /**
   * 批量删除
   */
  handleDelBatch = (selectedRowKeys) => {
    const that = this;
    Modal.confirm({
      title: `确定删除选中的 ${selectedRowKeys.length} 项 ?`,
      okText: "确认",
      cancelText: "取消",
      onOk() {
        that.props.dispatch({
          type: 'authMenu/delBatch',
          payload: selectedRowKeys
        })
      },
      onCancel() { },
    });
  }

  /**
   * 删除
   */
  handleDel = (record) => {
    const that = this;
    Modal.confirm({
      title: `确定删除此项 ?`,
      okText: "确认",
      cancelText: "取消",
      onOk() {
        that.props.dispatch({
          type: 'authMenu/del',
          payload: {
            menuId: record.menuId
          }
        })
      },
      onCancel() { },
    });
  }

  listData() {
    const { dispatch } = this.props;
    dispatch({
      type: 'authMenu/list'
    })
  }

  render() {
    const { loading, authMenu: { list } } = this.props;

    const {
      selectedRowKeys,
      modalVisible,
      stepFormValues,
    } = this.state;

    const rowSelection = {
      selectedRowKeys,
      onChange: this.handleSelectRows
    };

    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      handleUpdate: this.handleUpdate,
      handleAdd: this.handleAdd,
    };

    return (
      <PageHeaderWrapper title="菜单管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                新建
              </Button>
              {selectedRowKeys.length > 0 && (
                <span>
                  <Button icon="delete" onClick={() => this.handleDelBatch(selectedRowKeys)}>删除</Button>
                </span>
              )}
            </div>
            <div className={styles.tableAlert}>
              <Alert
                message={
                  <Fragment>
                    按 ID 大小进行排序, 顶级菜单父 ID 为 0
                  </Fragment>
                }
                type="info"
                showIcon
              />
            </div>
            <Table
              rowSelection={rowSelection}
              loading={loading}
              dataSource={list}
              columns={this.columns}
              rowKey="menuId"
              pagination="false"
            />
          </div>
        </Card>
        <AddOrUpdateForm
          {...parentMethods}
          modalVisible={modalVisible}
          values={stepFormValues}
        />
      </PageHeaderWrapper>
    )
  }
}

export default MenuList;